/**
 * 
 */
package com.newworld.dmsapp2.activity.serviceapply;

/**
 * @author long
 *维修申请界面
 */
import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.crud.DataSupport;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.InputFilter;
import android.text.format.DateFormat;
import android.text.format.Time;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TableLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.newworld.dmsapp2.BaseActivity;
import com.newworld.dmsapp2.R;
import com.newworld.dmsapp2.activity.MainActivity;
import com.newworld.dmsapp2.activity.SettingAccountActivity;
import com.newworld.dmsapp2.activity.UploadService;
import com.newworld.dmsapp2.bean.RelationHouse;
import com.newworld.dmsapp2.bean.RepairApply;
import com.newworld.dmsapp2.bean.User;
import com.newworld.dmsapp2.bean.UserAccount;
import com.newworld.dmsapp2.ui.adapter.AbstractSpinerAdapter;
import com.newworld.dmsapp2.ui.view.BadgeView;
import com.newworld.dmsapp2.ui.view.CustomDialog;
import com.newworld.dmsapp2.ui.view.CustomEditServiceStyleDialog;
import com.newworld.dmsapp2.ui.view.CustomLoadingDialog;
import com.newworld.dmsapp2.ui.view.DateAndTimeIntervalPickerDialog;
import com.newworld.dmsapp2.ui.view.CustomEditServiceStyleDialog.OnStateChagedListener1;
import com.newworld.dmsapp2.ui.view.DateAndTimeIntervalPickerDialog.OnDateSetListener;
import com.newworld.dmsapp2.ui.view.SpinerPopWindow;
import com.newworld.dmsapp2.util.Config;
import com.newworld.dmsapp2.util.HttpUtil;
import com.newworld.dmsapp2.util.SingleSample;
import com.newworld.dmsapp2.util.Tool;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

public class WritePaperActivity extends BaseActivity implements
		OnClickListener,AbstractSpinerAdapter.IOnItemSelectListener {
	public static TextView ser_start_time;
	public static String ser_start_time_str = "";
	private TextView ser_select_house;
	private String[] houses;
	private String[] houseids;
	private String[] housephones;

	private SpinerPopWindow mSpinerPopWindow;
	private ArrayList<String> houseList = new ArrayList<String>();
	private Button submitBtn;
	private Calendar c;
	private ImageView pictureFirstIv;
	private ImageView pictureNextIv;
	private TextView voiceTimeTv, righttx, phoneNumber;
	private ImageView voiceIv;
	private TextView titletext;
	private EditText repairObjectEdit;
	private EditText descriptEdit;
	private LinearLayout leftlayout;
	private String imageRealPath1 = "";
	private String imageRealPath2 = "";
	private Uri imageUri;
	private Intent intent;
	
	// 关系类型(亲戚，家人，租户)的id
	//protected AreaType areaType ;
	protected String areaType = Config.AREACODE_INDOOR;
	
	private String imagePath1 = "";
	private String voicePath = "";
	private String imagePath2 = "";
	private BadgeView badgeImage1;
	private BadgeView badgeImage2;
	private BadgeView badgeVoice;
	private String voiceTime;
	public static int flag = 0;
	// private static long REPAIR_ID = 0;
	private RepairApply repair;
	private User user;
	private UserAccount useraccount;
	private String houseid = "";
	private ProgressBar loginbar;
	private CustomLoadingDialog uploadingdialog;
	private String message;
	private String str = "及时上门";
	//private List<AreaType> areaTypeList = new ArrayList<AreaType>();
	
	@SuppressLint("HandlerLeak")
	Handler mHandler = new Handler() {

		@SuppressLint("NewApi")
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			switch (msg.what) {
			case Config.HANDLER_MSG_SUCCESS:
				if (uploadingdialog.isShowing()) {
					uploadingdialog.dismiss();
				} else {
					uploadingdialog.show();
				}
				deleteData();
				repair = user.getRepairapply();

				ser_select_house.setText(houseList.get(0));
				houseid = houseids[0];
				repairObjectEdit.setText(repair.getRepairObject());
				descriptEdit.setText(repair.getProblemDescript());
				ser_start_time.setText(repair.getExpectTime());
				imagePath1 = repair.getProblemImage1();
				imageRealPath2 = imageRealPath1;
				imagePath2 = imagePath1;
				badgeImage1.hide();
				ImageLoader.getInstance().displayImage(null, pictureFirstIv,
						options);
				pictureNextIv.setVisibility(View.INVISIBLE);
				badgeImage2.hide();
				ImageLoader.getInstance().displayImage(null, pictureNextIv,
						options);
				voicePath = repair.getProblemVoice();
				voiceTime = repair.getVoicetime();
				badgeVoice.hide();

				voiceTimeTv.setVisibility(View.INVISIBLE);
				voiceIv.setBackground(getResources().getDrawable(
						R.drawable.btn_voice_taken));
				onBackPressed();
				Toast.makeText(WritePaperActivity.this, (String) msg.obj,
						Toast.LENGTH_SHORT);
				break;
			case Config.HANDLER_MSG_GETDATA_SUCCESS:
				loginbar.setVisibility(android.view.View.INVISIBLE);
				repair = user.getRepairapply();
				int i = 0;
				if (null != repair && repair.getRelationhouses().size() > 0) {
					houses = new String[repair.getRelationhouses().size()];
					houseids = new String[repair.getRelationhouses().size()];
					housephones = new String[repair.getRelationhouses().size()];
					for (RelationHouse house : repair.getRelationhouses()) {
						phoneNumber.setText(house.getRepairPhone());
						houseList.add(house.getProjectName()
								+ house.getPhaseName()
								+ house.getBuildingName() + house.getUnitName()
								+ house.getHouseName());

						houses[i] = houseList.get(i);
						houseids[i] = house.getHouseId();
						housephones[i] = house.getRepairPhone();
						i++;
					}
				}
				if (null != houseList && houseList.size() > 0) {

					ser_select_house.setText(houseList.get(0));
					phoneNumber.setText(housephones[0]);
					houseid = houseids[0];
				} else {
					phoneNumber.setText("暂无");
					ser_select_house.setText("该用户未关联房屋");
				}
				
				Toast.makeText(WritePaperActivity.this, (String) msg.obj,
						Toast.LENGTH_SHORT);
				new Thread(getEditPersonRun).start();
				break;
			case Config.HANDLER_MSG_LOACALSAVE_SUCCESS:
				if (uploadingdialog.isShowing()) {
					uploadingdialog.dismiss();
				} else {
					uploadingdialog.show();
				}
				onBackPressed();
				Toast.makeText(WritePaperActivity.this, "保存成功",
						Toast.LENGTH_SHORT);
				break;
			case Config.HANDLER_MSG_FAIL:
				Toast.makeText(WritePaperActivity.this, "请设置网络",
						Toast.LENGTH_SHORT).show();
				if (uploadingdialog.isShowing()) {
					uploadingdialog.dismiss();
				} else {
					uploadingdialog.show();
				}
				loginbar.setVisibility(android.view.View.INVISIBLE);
				break;
			case Config.HANDLER_MSG_FAIL_1:
				Toast.makeText(WritePaperActivity.this, "请检查报修内容是否有误",
						Toast.LENGTH_SHORT).show();
				if (uploadingdialog.isShowing()) {
					uploadingdialog.dismiss();
				} else {
					uploadingdialog.show();
				}
				loginbar.setVisibility(android.view.View.INVISIBLE);
				break;
			case Config.HANDLER_MSG_FAIL_2:
				Toast.makeText(WritePaperActivity.this, "登录JSON解析出错",
						Toast.LENGTH_SHORT).show();
				if (uploadingdialog.isShowing()) {
					uploadingdialog.dismiss();
				} else {
					uploadingdialog.show();
				}
				loginbar.setVisibility(View.INVISIBLE);
				break;
			case Config.HANDLER_MSG_FAIL_3:
				message = (String) msg.obj;
				Toast.makeText(WritePaperActivity.this, message,
						Toast.LENGTH_SHORT).show();
				if (uploadingdialog.isShowing()) {
					uploadingdialog.dismiss();
				} else {
					uploadingdialog.show();
				}
				loginbar.setVisibility(android.view.View.INVISIBLE);
				break;
			case Config.HANDLER_MSG_JSON_LOGIN_FAIL:
				Toast.makeText(WritePaperActivity.this, "登陆JSON解析错误",
						Toast.LENGTH_SHORT).show();
				if (uploadingdialog.isShowing()) {
					uploadingdialog.dismiss();
				} else {
					uploadingdialog.show();
				}
				loginbar.setVisibility(android.view.View.INVISIBLE);
				break;
			default:
				break;
			}
			super.handleMessage(msg);
		}
	};
	private Toast toast;

	public static final DisplayImageOptions options = new DisplayImageOptions.Builder()

	.cacheInMemory(false) // 设置下载的图片是否缓存在内存中
			.cacheOnDisk(false).bitmapConfig(Bitmap.Config.RGB_565) // 设置下载的图片是否缓存在SD卡中
			.displayer(new RoundedBitmapDisplayer(10)) // 设置成圆角图片
			.build();

	@Override()
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_serviceapply_writepaper);
		initData();
		initViews();
		loginbar.setVisibility(View.VISIBLE);
		new Thread(getDataRun).start();
		initEvents();

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@SuppressLint("NewApi")
	@Override
	protected void initViews() {

		phoneNumber = (TextView) findViewById(R.id.phone_number);
		phoneNumber.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				// TODO Auto-generated method stub
				intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"
						+ phoneNumber.getText().toString()));
				startActivity(intent);
			}
		});
		titletext = (TextView) findViewById(R.id.titlebar_both_center_title);
		titletext.setText("户内报修");
		righttx = (TextView) findViewById(R.id.titlebar_both_right_text);
		righttx.setText("清空");
		leftlayout = (LinearLayout) findViewById(R.id.titlebar_both_left_layout);
		leftlayout.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				uploadingdialog = new CustomLoadingDialog(
						WritePaperActivity.this, "正在保存...");
				if (uploadingdialog.isShowing()) {
					uploadingdialog.isShowing();
					uploadingdialog.dismiss();
				} else {
					uploadingdialog.show();
				}
				new Thread(saveDataRun).start();

			}
		});
		loginbar = (ProgressBar) findViewById(R.id.writepaper_progressBar);

		// btn_write_next = (Button)findViewById(R.id.ser_writepaper_btn);
		ser_select_house = (TextView) findViewById(R.id.ser_select_house);

		ser_start_time = (TextView) findViewById(R.id.ser_start_time);
		submitBtn = (Button) findViewById(R.id.btn_submit);
		pictureFirstIv = (ImageView) findViewById(R.id.iv_picture_first);
		pictureNextIv = (ImageView) findViewById(R.id.iv_picture_next);
		voiceTimeTv = (TextView) findViewById(R.id.tv_voice_time);
		voiceIv = (ImageView) findViewById(R.id.iv_voice);
		repairObjectEdit = (EditText) findViewById(R.id.repair_object_edit);
		repairObjectEdit
				.setFilters(new InputFilter[] { new InputFilter.LengthFilter(20) });
		descriptEdit = (EditText) findViewById(R.id.descript_edit);
		descriptEdit
				.setFilters(new InputFilter[] { new InputFilter.LengthFilter(
						120) });
		badgeImage1 = new BadgeView(this, pictureFirstIv);
		badgeImage2 = new BadgeView(this, pictureNextIv);
		badgeVoice = new BadgeView(this, voiceIv);

		c = Calendar.getInstance();

		LinearLayout rightlayout = (LinearLayout) findViewById(R.id.titlebar_both_right_layout);
		rightlayout.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				deleteData();

				repair = user.getRepairapply();
				if (null != houseList && houseList.size() > 0) {
					ser_select_house.setText(houseList.get(0));
					houseid = houseids[0];
					phoneNumber.setText(housephones[0]);
				} else {
					ser_select_house.setText("该用户未关联房屋");
					phoneNumber.setText("暂无");
				}

				repairObjectEdit.setText(repair.getRepairObject());
				descriptEdit.setText(repair.getProblemDescript());
				ser_start_time.setText(repair.getExpectTime());
				imagePath1 = repair.getProblemImage1();
				imageRealPath2 = imageRealPath1;
				imagePath2 = imagePath1;
				badgeImage1.hide();
				ImageLoader.getInstance().displayImage(null, pictureFirstIv,
						options);
				pictureNextIv.setVisibility(View.INVISIBLE);
				badgeImage2.hide();
				ImageLoader.getInstance().displayImage(null, pictureNextIv,
						options);
				voicePath = repair.getProblemVoice();
				voiceTime = repair.getVoicetime();
				badgeVoice.hide();

				voiceTimeTv.setVisibility(View.INVISIBLE);
				voiceIv.setBackground(getResources().getDrawable(
						R.drawable.btn_voice_taken));
				if (null != repair.getHouseName()
						&& !repair.getHouseName().equals("")) {
					ser_select_house.setText(repair.getHouseName());
					houseid = repair.getHouseId();
				}
				if (null != repair.getRepairPhone()
						&& !repair.getRepairPhone().equals("")) {
					phoneNumber.setText(repair.getRepairPhone());
				}
				if (null != repair.getRepairObject()
						&& !repair.getRepairObject().equals("")) {
					repairObjectEdit.setText(repair.getRepairObject());
				}
				if (null != repair.getProblemDescript()
						&& !repair.getProblemDescript().equals("")) {
					descriptEdit.setText(repair.getProblemDescript());
				}
				if (null != repair.getExpectTime()
						&& !repair.getExpectTime().equals("")) {
					ser_start_time.setText(repair.getExpectTime());
				}
				if (null != repair.getProblemImage1()
						&& !repair.getProblemImage1().equals("")) {
					imagePath1 = repair.getProblemImage1();
					imageRealPath1 = Config.IMAGE_PATH + imagePath1;
				}
				if (null != repair.getProblemImage2()
						&& !repair.getProblemImage2().equals("")) {
					imagePath2 = repair.getProblemImage2();
					imageRealPath2 = Config.IMAGE_PATH + imagePath2;
				}
				if (null != repair.getProblemVoice()
						&& !repair.getProblemVoice().equals("")) {
					voicePath = repair.getProblemVoice();
					voiceTime = repair.getVoicetime();
				}
				if (null != imagePath1 && !imagePath1.equals("")) {

					badgeImage1.setText("  ");
					badgeImage1.setTextSize(12);
					badgeImage1.setBackgroundResource(R.drawable.badge_view);
					badgeImage1.setBadgePosition(BadgeView.POSITION_TOP_RIGHT);
					badgeImage1.setBadgeMargin(0, 0);
					badgeImage1.toggle();
					badgeImage1.show();
					badgeImage1.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							imageRealPath1 = imageRealPath2;
							imagePath1 = imagePath2;
							imagePath2 = "";
							imageRealPath2 = "";

							if (imagePath1.equals("")) {
								badgeImage1.hide();
								ImageLoader.getInstance().displayImage(null,
										pictureFirstIv, options);

								pictureNextIv.setVisibility(View.INVISIBLE);
							} else {
								badgeImage2.hide();
								ImageLoader.getInstance().displayImage(
										"file://" + Config.IMAGE_PATH
												+ imagePath1, pictureFirstIv,
										options);
								ImageLoader.getInstance().displayImage(null,
										pictureNextIv, options);

							}
						}
					});
					ImageLoader.getInstance().displayImage(
							"file://" + Config.IMAGE_PATH + imagePath1,
							pictureFirstIv, options);

					pictureNextIv.setVisibility(View.VISIBLE);
				}
				if (!imagePath2.equals("")) {
					badgeImage2.setText("  ");
					badgeImage2.setTextSize(12);
					badgeImage2.setBackgroundResource(R.drawable.badge_view);
					badgeImage2.setBadgePosition(BadgeView.POSITION_TOP_RIGHT);
					badgeImage2.setBadgeMargin(0, 0);
					badgeImage2.toggle();
					badgeImage2.show();
					badgeImage2.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							imagePath2 = "";
							imageRealPath2 = "";
							badgeImage2.hide();
							ImageLoader.getInstance().displayImage(null,
									pictureNextIv, options);

						}
					});
					ImageLoader.getInstance().displayImage(
							"file://" + Config.IMAGE_PATH + imagePath2,
							pictureNextIv, options);
				}

				if (!voicePath.equals("")) {

					badgeVoice.setText("  ");
					badgeVoice.setTextSize(12);
					badgeVoice.setBadgePosition(BadgeView.POSITION_TOP_RIGHT);

					badgeVoice.setBackgroundResource(R.drawable.badge_view);
					badgeVoice.setBadgeMargin(0, 0);
					badgeVoice.toggle();
					badgeVoice.show();
					badgeVoice.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub

							badgeVoice.hide();
							voicePath = "";
							voiceTimeTv.setVisibility(View.INVISIBLE);
							voiceIv.setBackgroundResource(R.drawable.btn_voice_taken);
						}
					});

					voiceTimeTv.setVisibility(View.VISIBLE);
					voiceTimeTv.setText(voiceTime + "'");
				}
			}
		});
		if (null != user.getRepairapply()) {
			repair = user.getRepairapply();

			if (null != repair.getRepairObject()
					&& !repair.getRepairObject().equals("")) {
				repairObjectEdit.setText(repair.getRepairObject());
			}
			if (null != repair.getProblemDescript()
					&& !repair.getProblemDescript().equals("")) {
				descriptEdit.setText(repair.getProblemDescript());
			}
			if (null != repair.getExpectTime()
					&& !repair.getExpectTime().equals("")) {
				ser_start_time.setText(repair.getExpectTime());
			}
			if (null != repair.getProblemImage1()
					&& !repair.getProblemImage1().equals("")) {
				imagePath1 = repair.getProblemImage1();
				imageRealPath1 = Config.IMAGE_PATH + imagePath1;
			}
			if (null != repair.getProblemImage2()
					&& !repair.getProblemImage2().equals("")) {
				imagePath2 = repair.getProblemImage2();
				imageRealPath2 = Config.IMAGE_PATH + imagePath2;
			}
			if (null != repair.getProblemVoice()
					&& !repair.getProblemVoice().equals("")) {
				voicePath = repair.getProblemVoice();
				voiceTime = repair.getVoicetime();
			}
		}
		if (null != imagePath1 && !imagePath1.equals("")) {

			badgeImage1.setText("  ");
			badgeImage1.setTextSize(12);
			badgeImage1.setBackgroundResource(R.drawable.badge_view);
			badgeImage1.setBadgePosition(BadgeView.POSITION_TOP_RIGHT);
			badgeImage1.setBadgeMargin(0, 0);
			badgeImage1.toggle();
			badgeImage1.show();
			badgeImage1.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					imageRealPath1 = imageRealPath2;
					imagePath1 = imagePath2;
					imagePath2 = "";
					imageRealPath2 = "";

					if (imagePath1.equals("")) {
						badgeImage1.hide();
						ImageLoader.getInstance().displayImage(null,
								pictureFirstIv, options);

						pictureNextIv.setVisibility(View.INVISIBLE);
					} else {
						badgeImage2.hide();
						ImageLoader.getInstance().displayImage(
								"file://" + Config.IMAGE_PATH + imagePath1,
								pictureFirstIv, options);
						ImageLoader.getInstance().displayImage(null,
								pictureNextIv, options);

					}
				}
			});
			ImageLoader.getInstance().displayImage(
					"file://" + Config.IMAGE_PATH + imagePath1, pictureFirstIv,
					options);

			pictureNextIv.setVisibility(View.VISIBLE);
		}
		if (!imagePath2.equals("")) {
			badgeImage2.setText("  ");
			badgeImage2.setTextSize(12);
			badgeImage2.setBackgroundResource(R.drawable.badge_view);
			badgeImage2.setBadgePosition(BadgeView.POSITION_TOP_RIGHT);
			badgeImage2.setBadgeMargin(0, 0);
			badgeImage2.toggle();
			badgeImage2.show();
			badgeImage2.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					imagePath2 = "";
					imageRealPath2 = "";
					badgeImage2.hide();
					ImageLoader.getInstance().displayImage(null, pictureNextIv,
							options);

				}
			});
			ImageLoader.getInstance().displayImage(
					"file://" + Config.IMAGE_PATH + imagePath2, pictureNextIv,
					options);
		}

		if (!voicePath.equals("")) {
			voiceIv.setBackground(getResources().getDrawable(
					R.drawable.record_voice));
			badgeVoice.setText("  ");
			badgeVoice.setTextSize(12);
			badgeVoice.setBadgePosition(BadgeView.POSITION_TOP_RIGHT);

			badgeVoice.setBackgroundResource(R.drawable.badge_view);
			badgeVoice.setBadgeMargin(0, 0);
			badgeVoice.toggle();
			badgeVoice.show();
			badgeVoice.setOnClickListener(new OnClickListener() {
				@SuppressLint("NewApi")
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub

					badgeVoice.hide();
					voicePath = "";
					voiceTimeTv.setVisibility(View.INVISIBLE);
					voiceIv.setBackground(getResources().getDrawable(
							R.drawable.btn_voice_taken));
				}
			});

			voiceTimeTv.setVisibility(View.VISIBLE);
			voiceTimeTv.setText(voiceTime + "'");
		}

		mSpinerPopWindow = new SpinerPopWindow(this);
		mSpinerPopWindow.refreshData(houseList, 0);
		if (null != houseList && houseList.size() > 0) {
			ser_select_house.setText(houseList.get(0));
			houseid = houseids[0];
			phoneNumber.setText(housephones[0]);
		} else {
			phoneNumber.setText("暂无");
			ser_select_house.setText("该用户未关联房屋");
		}
//初始化上门方式和时间
		Time t = new Time();
		t.setToNow();
		int currenthour = t.hour;
		int currenthourmax = currenthour + 1;
		int nowyearint = t.year;
		int nowmonthint = t.month + 1;
		int nowdayint = t.monthDay;
		System.out.print("当前小时为：" + currenthour);
		String dayString;
		String timeInterval;
		String yearstr,monthstr,daystr;
		if (nowyearint < 10) {
			yearstr = "0" + nowyearint;
		} else {
			yearstr = nowyearint + "";
		}
		if (nowmonthint < 10) {
			monthstr = "0" + nowmonthint;

		} else {
			monthstr = nowmonthint + "";
		}
		if (nowdayint < 10) {
			daystr = "0" + nowdayint;
		} else {
			daystr = nowdayint + "";
		}
		if(currenthourmax < 13){
			currenthourmax = 15;
			timeInterval =  "14:00~15:00" ;
			dayString = yearstr + "-" + monthstr + "-"
				+ daystr;
		} else{
			currenthourmax = 9;
			timeInterval = "08:00~09:00";
			nowdayint = nowdayint +1;
			if (nowdayint < 10) {
				daystr = "0" + nowdayint;
			} else {
				daystr = nowdayint + "";
			}
			dayString = yearstr + "-" + monthstr + "-"
				+ daystr;
		}
		if(Config.AREAFLAG){
			WriteOutdoorPaperActivity.outdoor_ser_start_time.setText("及时上门");
			WriteOutdoorPaperActivity.outdoor_ser_start_time_str = dayString + " "
					+ timeInterval;
		} else{
			WritePaperActivity.ser_start_time.setText("及时上门");
			WritePaperActivity.ser_start_time_str = dayString + " "
					+ timeInterval;
		}
	}

	private void initData() {
		Config.AREAFLAG = false;
		user = SingleSample.getInstance(this).getUser();
		if(user.getUseraccounts()!=null && !user.getUseraccounts().isEmpty()){
			if(user.getUseraccounts().get(0) != null){
				useraccount = user.getUseraccounts().get(0);
			}else{
				Toast.makeText(WritePaperActivity.this, "未获取用户信息", Toast.LENGTH_SHORT).show();
			}
		}else{
			Toast.makeText(WritePaperActivity.this, "未获取用户信息", Toast.LENGTH_SHORT).show();
		}
		
	}

	@Override
	protected void initEvents() {
		// btn_write_next.setOnClickListener(this);

		ser_select_house.setOnClickListener(this);
		ser_start_time.setOnClickListener(this);
		mSpinerPopWindow.setItemListener(this);
		submitBtn.setOnClickListener(this);
		pictureFirstIv.setOnClickListener(this);
		pictureNextIv.setOnClickListener(this);
		voiceIv.setOnClickListener(this);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	@SuppressLint("NewApi")
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.ser_select_house://选择房屋
			// showListDialog(ser_select_house, this, houses, listener);
				showSpinWindow();
			break;
		case R.id.ser_start_time:
			final CustomEditServiceStyleDialog dialog11 = new CustomEditServiceStyleDialog(
					WritePaperActivity.this);
			//str = sexEdit.getText() + "";
			dialog11.setDetial(str);
			dialog11.setTitle("维修方式选择");
			dialog11.show();
			dialog11.setOnStateChagedListener1(new OnStateChagedListener1() {

				@Override
				public void onStateChanged(String str) {
					// TODO Auto-generated method stub
					ser_start_time.setText(str);
					//userSexstr = sexEdit.getText().toString();
					//logInbar.setVisibility(View.VISIBLE);
					//new Thread(postEditPersonRun).start();
					dialog11.dismiss();
				}
			});
			/*new DateAndTimeIntervalPickerDialog(WritePaperActivity.this,
					new OnDateSetListener() {

						private Toast toast;

						@Override
						public void onDateSet(Calendar calendar,
								String timeInterval) {
							// TODO Auto-generated method stub
							Date dateNow = new Date();

							String dayString;
							String yearstr, monthstr, daystr;

							int yearint, monthint, dayint;

							String hour = timeInterval.substring(0, 2);
							Time t = new Time();
							t.setToNow();
							int currenthour = t.hour;
							int currenthourmax = currenthour + 1;
							int nowyearint = t.year;
							int nowmonthint = t.month + 1;
							int nowdayint = t.monthDay;
							int mhour = Integer.parseInt(hour);
							System.out.print("当前小时为：" + currenthour);
							System.out.print("日历小时为：" + hour);

							yearint = calendar.get(Calendar.YEAR);
							monthint = calendar.get(Calendar.MONTH) + 1;
							dayint = calendar.get(Calendar.DAY_OF_MONTH);
							Log.e("选择时间", yearint + "+" + monthint + "+" + dayint);
							calendar.set(yearint, monthint - 1, dayint, mhour,
									0, 0);
							Date date = calendar.getTime();
							int daybetween = daysBetween(dateNow, date);
							int timebetween = timeBetween(dateNow, date);
							System.out.println("daybetween____" + daybetween);
							Log.e("WriteOutdoorPaperActivity>>>daybetween",
									"daybetween = " + daybetween);
							if (date.before(dateNow)
									|| ((yearint == nowyearint)
											&& (monthint == nowmonthint)
											&& (dayint == nowdayint) && (timebetween < 2))) {
								toast = Toast.makeText(
										WritePaperActivity.this,
										"请选择当前时间两个小时之后的时间", Toast.LENGTH_SHORT);
								toast.setGravity(Gravity.CENTER, 0, 0);
								toast.show();
								if (nowyearint < 10) {
									yearstr = "0" + yearint;
								} else {
									yearstr = yearint + "";
								}
								if (monthint < 10) {
									monthstr = "0" + monthint;

								} else {
									monthstr = monthint + "";
								}
								if (dayint < 10) {
									daystr = "0" + dayint;
								} else {
									daystr = dayint + "";
								}
								if (currenthour < 9) {
									timeInterval = "0" + currenthour + ":00"
											+ "~" + "0" + currenthourmax
											+ ":00";
								} else if (currenthour == 9) {
									timeInterval = "0" + currenthour + ":00"
											+ "~" + currenthourmax + ":00";
								} else {
									timeInterval = currenthour + ":00" + "~"
											+ currenthourmax + ":00";
								}
								dayString = yearstr + "-" + monthstr + "-"
										+ daystr;
								ser_start_time.setText(dayString + " "
										+ timeInterval);

							} else if (daybetween <= 6) {// 从当天开始计算
								if (yearint < 10) {
									yearstr = "0" + yearint;
								} else {
									yearstr = yearint + "";
								}
								
								if (monthint < 10) {
									if (monthint == 1) {
										// nowmonthint = nowmonthint+1;
										monthstr = "0" + monthint;
									}
									monthstr = "0" + monthint;

								} else {
									monthstr = monthint + "";
								}
								if (dayint < 10) {
									daystr = "0" + dayint;
								} else {
									daystr = dayint + "";
								}
								dayString = yearstr + "-" + monthstr + "-"
										+ daystr;
								ser_start_time.setText(dayString + " "
										+ timeInterval);

							} else {
								toast = Toast.makeText(
										WritePaperActivity.this,
										"请选择未来七天之内的时间", Toast.LENGTH_SHORT);
								toast.setGravity(Gravity.CENTER, 0, 0);
								toast.show();
								if (yearint < 10) {
									yearstr = "0" + yearint;
								} else {
									yearstr = yearint + "";
								}
								if (monthint < 10) {
									monthstr = "0" + monthint;
								} else {
									monthstr = monthint + "";
								}
								if (dayint < 10) {
									daystr = "0" + dayint;
								} else {
									daystr = dayint + "";
								}
								if (currenthour < 9) {
									timeInterval = "0" + currenthour + ":00"
											+ "~" + "0" + currenthourmax
											+ ":00";
								} else if (currenthour == 9) {
									timeInterval = "0" + currenthour + ":00"
											+ "~" + currenthourmax + ":00";
								} else {
									timeInterval = currenthour + ":00" + "~"
											+ currenthourmax + ":00";
								}
								dayString = yearstr + "-" + monthstr + "-"
										+ daystr;
								ser_start_time.setText(dayString + " "
										+ timeInterval);
							}
						}
					}, c).show();
*/
			break;

		case R.id.btn_submit:
			/* String repairobject=repairObjectEdit.getText().toString(); */
			if (ser_select_house.getText().toString().equals("")) {
				toast = Toast.makeText(WritePaperActivity.this, "请选择房屋",
						Toast.LENGTH_LONG);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();
			} else if (repairObjectEdit.getText().toString().equals("")) {

				toast = Toast.makeText(WritePaperActivity.this, "请填写修维修内容",
						Toast.LENGTH_LONG);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();

			} else if (ser_start_time.getText().toString().equals("")) {

				toast = Toast.makeText(WritePaperActivity.this, "请选择期望上门时间",
						Toast.LENGTH_LONG);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();

			} else if (!ser_start_time.getText().toString().equals("")
					&& !repairObjectEdit.getText().toString().equals("")
					&& !ser_select_house.getText().toString().equals("")) {
				if(user.getUseraccounts()!=null && !user.getUseraccounts().isEmpty()){
					if(user.getUseraccounts().get(0) != null){
						if((null != useraccount.getMobilePhone() && !useraccount.getMobilePhone().equals(""))
								&&(null != useraccount.getRealName() && !useraccount.getRealName().equals(""))){
							final CustomDialog dialog = new CustomDialog(
									WritePaperActivity.this);
							dialog.setTitle("维修申请");
							dialog.setDetial("是否确认提交？");
							dialog.setLeftOnClick(new OnClickListener() {
								@Override
								public void onClick(View v) {

									dialog.dismiss();

								}
							});
							dialog.show();
							dialog.setRightOnClick(new OnClickListener() {

								@Override
								public void onClick(View v) {
									dialog.dismiss();
									uploadingdialog = new CustomLoadingDialog(
											WritePaperActivity.this, "正在上传...");
									if (uploadingdialog.isShowing()) {
										uploadingdialog.dismiss();

									} else {
										uploadingdialog.show();
									}
									if(Tool.isNetworkAvailable(WritePaperActivity.this)){
										new Thread(uploadfile).start();
									}else{
										mHandler.obtainMessage(Config.HANDLER_MSG_FAIL, "联网失败")
										.sendToTarget();
									}
								}
							});
							dialog.show();
						}else{
							final CustomDialog dialog = new CustomDialog(
									WritePaperActivity.this);
							dialog.setTitle("设置个人信息");
							dialog.setDetial("提单请先设置联系电话和姓名");
							dialog.setLeftOnClick(new OnClickListener() {
								@Override
								public void onClick(View v) {

									dialog.dismiss();
									
								}
							});
							dialog.show();
							dialog.setRightOnClick(new OnClickListener() {

								@Override
								public void onClick(View v) {
									dialog.dismiss();
									uploadingdialog = new CustomLoadingDialog(WritePaperActivity.this,
											"正在保存...");
									if (uploadingdialog.isShowing()) {
										uploadingdialog.dismiss();
									} else {
										uploadingdialog.show();
									}
									new Thread(saveDataRun).start();
									Intent intent = new Intent();
									intent.setClass(WritePaperActivity.this, SettingAccountActivity.class);
									startActivity(intent);

								}
							});
							dialog.show();
						}
					}else{
						Toast.makeText(WritePaperActivity.this, "未获取用户联系电话", Toast.LENGTH_SHORT).show();
					}
				}else{
					Toast.makeText(WritePaperActivity.this, "未获取用户联系电话", Toast.LENGTH_SHORT).show();
				}
				
				
			}
			break;
		case R.id.iv_picture_first:
			if (imagePath1.equals("")) {

				final Dialog dlg = new Dialog(this, R.style.ActionSheet);
				LayoutInflater inflater = (LayoutInflater) this
						.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				LinearLayout layout = (LinearLayout) inflater.inflate(
						R.layout.activity_writepaper_dialog, null);
				final int cFullFillWidth = 10000;
				layout.setMinimumWidth(cFullFillWidth);

				TextView mContent1 = (TextView) layout
						.findViewById(R.id.tv_content1);
				TextView mContent2 = (TextView) layout
						.findViewById(R.id.tv_content2);
				TextView mCancel = (TextView) layout
						.findViewById(R.id.tv_cancel);
				// 拍摄选择照片
				mContent1.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						String temName = DateFormat.format("yyMMdd_hhmmss",
								System.currentTimeMillis())
								+ "_"
								+ (Math.random() * 100) + ".jpg";
						imageRealPath1 = Config.IMAGE_PATH + File.separator
								+ temName;
						File file = new File(imageRealPath1);
						if (file.exists()) {
							file.delete();
						}
						imageUri = Uri.fromFile(file);
						Intent intent = new Intent(
								MediaStore.ACTION_IMAGE_CAPTURE);

						intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
						startActivityForResult(intent, 1);

						dlg.dismiss();
					}
				});
				// 从相册中选择照片
				mContent2.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						Intent choosePictureIntent = new Intent(
								Intent.ACTION_PICK,
								android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
						choosePictureIntent.setType("image/jpeg");
						startActivityForResult(choosePictureIntent, 2);
						dlg.dismiss();
					}
				});

				mCancel.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub

						dlg.dismiss();

					}
				});

				Window w = dlg.getWindow();
				WindowManager.LayoutParams lp = w.getAttributes();
				lp.x = 0;
				final int cMakeBottom = -1000;
				lp.y = cMakeBottom;
				lp.gravity = Gravity.BOTTOM;
				dlg.onWindowAttributesChanged(lp);
				dlg.setCanceledOnTouchOutside(false);
				dlg.setContentView(layout);
				dlg.show();
			}
			// 已经有图片了就直接放大显示
			else {

				Intent intent = new Intent(this, ViewPagerActivity.class);
				intent.putExtra("image1", "file://" + imageRealPath1);

				if (!imagePath2.equals("")) {
					intent.putExtra("image2", "file://" + imageRealPath2);
				}

				startActivity(intent);
			}
			break;
		case R.id.iv_picture_next:
			if (imagePath2.equals("")) {

				final Dialog dlg = new Dialog(this, R.style.ActionSheet);
				LayoutInflater inflater = (LayoutInflater) this
						.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				LinearLayout layout = (LinearLayout) inflater.inflate(
						R.layout.activity_writepaper_dialog, null);
				final int cFullFillWidth = 10000;
				layout.setMinimumWidth(cFullFillWidth);

				TextView mContent1 = (TextView) layout
						.findViewById(R.id.tv_content1);
				TextView mContent2 = (TextView) layout
						.findViewById(R.id.tv_content2);
				TextView mCancel = (TextView) layout
						.findViewById(R.id.tv_cancel);
				// 拍摄选择照片
				mContent1.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						String temName = DateFormat.format("yyMMdd_hhmmss",
								System.currentTimeMillis())
								+ "_"
								+ (Math.random() * 100) + ".jpg";
						imageRealPath2 = Config.IMAGE_PATH + File.separator
								+ temName;
						File file = new File(imageRealPath2);
						if (file.exists()) {
							file.delete();
						}
						imageUri = Uri.fromFile(file);
						Intent intent = new Intent(
								MediaStore.ACTION_IMAGE_CAPTURE);

						intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
						startActivityForResult(intent, 3);

						dlg.dismiss();
					}
				});
				// 从相册中选择照片
				mContent2.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						Intent choosePictureIntent = new Intent(
								Intent.ACTION_PICK,
								android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
						choosePictureIntent.setType("image/jpeg");
						startActivityForResult(choosePictureIntent, 4);
						dlg.dismiss();
					}
				});

				mCancel.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						dlg.dismiss();
					}
				});

				Window w = dlg.getWindow();
				WindowManager.LayoutParams lp = w.getAttributes();
				lp.x = 0;
				final int cMakeBottom = -1000;
				lp.y = cMakeBottom;
				lp.gravity = Gravity.BOTTOM;
				dlg.onWindowAttributesChanged(lp);
				dlg.setCanceledOnTouchOutside(false);
				dlg.setContentView(layout);
				dlg.show();
			} else {
				Intent intent = new Intent(this, ViewPagerActivity.class);
				intent.putExtra("image1", "file://" + imageRealPath2);
				intent.putExtra("image2", "file://" + imageRealPath1);
				startActivity(intent);
			}
			break;
		case R.id.iv_voice:
			if (voicePath.equals("")) {
				File parent2 = new File("/sdcard/NewWorld_APP2_Voice/");
				if (!parent2.exists()) {
					parent2.mkdirs();
				}
				Intent intent = new Intent(WritePaperActivity.this,
						SoundActivity.class);
				startActivityForResult(intent, 7);
			} else {
				/*
				 * voiceIv.setBackground(getResources().getDrawable(
				 * R.drawable.record_voice));
				 */
				File clickfile = new File(Config.VOICE_PATH + voicePath);
				Intent it = new Intent();
				it.setAction(Intent.ACTION_VIEW);

				it.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				it.putExtra("oneshot", 0);
				it.putExtra("configchange", 0);
				it.setDataAndType(Uri.parse("file:" + clickfile.getPath()),
						"audio/*");
				startActivity(it);
			}

			break;
		default:
			break;
		}
	}

	/**
	 * 计算两个日期之间相差的天数
	 * 
	 * @param date1
	 * @param date2
	 * @return
	 */
	public static int daysBetween(Date date1, Date date2) {
		//Calendar cal = Calendar.getInstance();
		//cal.setTime(date1);
		long time1 = date1.getTime();
		//cal.setTime(date2);
		long time2 = date2.getTime();
		 long intervalMilli = time2-time1;

		return (int)(intervalMilli/ (1000 * 3600 * 24));
	}
	
	/**
	 * 计算两个日期之间相差的小时数
	 * 
	 * @param date1
	 * @param date2
	 * @return
	 */
	public static int timeBetween(Date date1, Date date2) {
		long time1 = date1.getTime();
		long time2 = date2.getTime();
		 long intervalMilli = time2-time1;

		return (int)(intervalMilli/ (1000 * 3600));
	}
	public static int daysOfTwo(Date fDate, Date oDate) {

	       Calendar aCalendar = Calendar.getInstance();

	       aCalendar.setTime(fDate);

	       int day1 = aCalendar.get(Calendar.DAY_OF_YEAR);

	       aCalendar.setTime(oDate);

	       int day2 = aCalendar.get(Calendar.DAY_OF_YEAR);

	       return day2 - day1;

	    }
	

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) { // 监控/拦截/屏蔽返回键
			uploadingdialog = new CustomLoadingDialog(WritePaperActivity.this,
					"正在保存...");
			if (uploadingdialog.isShowing()) {
				uploadingdialog.dismiss();
			} else {
				uploadingdialog.show();
			}
			new Thread(saveDataRun).start();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	/**
	 * 下拉列表的点击事件
	 */
	@Override
	public void onItemClick(int pos) {
		// TODO Auto-generated method stub
		if (pos >= 0 && pos <= houseList.size()) {

			ser_select_house.setText(houseList.get(pos));

			houseid = houseids[pos];
			
			phoneNumber.setText(housephones[pos]);
		}
	}

	/*
	 * 弹出下拉框，选择房屋
	 */

	private void showSpinWindow() {
		Log.e("", "showSpinWindow");
		mSpinerPopWindow.setWidth(LayoutParams.MATCH_PARENT);
		mSpinerPopWindow.showAtLocation(WritePaperActivity.this.findViewById(R.id.repair_container),  
				Gravity.LEFT|Gravity.BOTTOM, 0, 0);
	}

	@SuppressLint("NewApi")
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == Activity.RESULT_OK && requestCode == 1) {
			Bundle b = new Bundle();
			b.putString("imagePath", imageRealPath1);
			Intent intent = new Intent(WritePaperActivity.this,
					ChoosephotoActivity.class);
			flag = 1;
			intent.putExtras(b);
			startActivityForResult(intent, 5);
		} else if (resultCode == Activity.RESULT_OK && requestCode == 2) {
			Bundle bundle = new Bundle();
			Uri uri = data.getData();

			String[] filePathColumn = { MediaStore.Images.Media.DATA };
			Log.e("picture", uri.toString());
			Cursor cursor = getContentResolver().query(uri, filePathColumn,
					null, null, null);
			cursor.moveToFirst();

			int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
			imageRealPath1 = cursor.getString(columnIndex);
			cursor.close();
			bundle.putString("imagePath", imageRealPath1);
			Intent intent = new Intent(WritePaperActivity.this,
					ChoosephotoActivity.class);
			flag = 2;
			intent.putExtras(bundle);
			startActivityForResult(intent, 5);
		}

		else if (resultCode == Activity.RESULT_OK && requestCode == 3) {
			Bundle b1 = new Bundle();
			b1.putString("imagePath", imageRealPath2);
			Intent intent1 = new Intent(WritePaperActivity.this,
					ChoosephotoActivity.class);
			flag = 1;
			intent1.putExtras(b1);
			startActivityForResult(intent1, 6);
		} else if (resultCode == Activity.RESULT_OK && requestCode == 4) {
			Bundle bundle = new Bundle();
			Uri uri = data.getData();
			String[] filePathColumn = { MediaStore.Images.Media.DATA };
			Log.e("picture", uri.toString());
			Cursor cursor = getContentResolver().query(uri, filePathColumn,
					null, null, null);
			cursor.moveToFirst();

			int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
			imageRealPath2 = cursor.getString(columnIndex);
			cursor.close();
			bundle.putString("imagePath", imageRealPath2);
			Intent intent = new Intent(WritePaperActivity.this,
					ChoosephotoActivity.class);
			flag = 2;
			intent.putExtras(bundle);
			startActivityForResult(intent, 6);
		} else if (resultCode == Activity.RESULT_OK && requestCode == 5) {
			imagePath1 = data.getStringExtra("imagePath");
			imageRealPath1 = Config.IMAGE_PATH + imagePath1;
		} else if (resultCode == Activity.RESULT_OK && requestCode == 6) {
			imagePath2 = data.getStringExtra("imagePath");
			imageRealPath2 = Config.IMAGE_PATH + imagePath2;
		} else if (resultCode == Activity.RESULT_OK && requestCode == 7) {
			voicePath = data.getStringExtra("voiceName");
			voiceTime = data.getIntExtra("voiceTime", 0) + "";
		}else if (resultCode == Activity.RESULT_OK && requestCode == 8) {
			if (data != null) {
				Bundle bundle = data.getExtras(); // data为B中回传的Intent
				String houseStr = bundle.getString("houseFullName");// str即为回传的值
				houseid = bundle.getString("houseID");
				
				ser_select_house.setText(houseStr);
			}
		}

		if (!imagePath1.equals("")) {

			badgeImage1.setText("  ");
			badgeImage1.setTextSize(12);
			badgeImage1.setBackgroundResource(R.drawable.badge_view);
			badgeImage1.setBadgePosition(BadgeView.POSITION_TOP_RIGHT);
			badgeImage1.setBadgeMargin(0, 0);
			badgeImage1.toggle();
			badgeImage1.show();
			badgeImage1.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					imageRealPath1 = imageRealPath2;
					imagePath1 = imagePath2;
					imagePath2 = "";
					imageRealPath2 = "";

					if (imagePath1.equals("")) {
						badgeImage1.hide();
						ImageLoader.getInstance().displayImage(null,
								pictureFirstIv, options);

						pictureNextIv.setVisibility(View.INVISIBLE);
					} else {
						badgeImage2.hide();
						ImageLoader.getInstance().displayImage(
								"file://" + Config.IMAGE_PATH + imagePath1,
								pictureFirstIv, options);
						ImageLoader.getInstance().displayImage(null,
								pictureNextIv, options);

					}
				}
			});
			ImageLoader.getInstance().displayImage(
					"file://" + Config.IMAGE_PATH + imagePath1, pictureFirstIv,
					options);

			pictureNextIv.setVisibility(View.VISIBLE);
		}
		if (!imagePath2.equals("")) {
			badgeImage2.setText("  ");
			badgeImage2.setTextSize(12);
			badgeImage2.setBackgroundResource(R.drawable.badge_view);
			badgeImage2.setBadgePosition(BadgeView.POSITION_TOP_RIGHT);
			badgeImage2.setBadgeMargin(0, 0);
			badgeImage2.toggle();
			badgeImage2.show();
			badgeImage2.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					imagePath2 = "";
					imageRealPath2 = "";
					badgeImage2.hide();
					ImageLoader.getInstance().displayImage(null, pictureNextIv,
							options);

				}
			});
			ImageLoader.getInstance().displayImage(
					"file://" + Config.IMAGE_PATH + imagePath2, pictureNextIv,
					options);
		}

		if (!voicePath.equals("")) {
			voiceIv.setBackground(getResources().getDrawable(
					R.drawable.record_voice));
			badgeVoice.setText("  ");
			badgeVoice.setTextSize(12);
			badgeVoice.setBadgePosition(BadgeView.POSITION_TOP_RIGHT);
			badgeVoice.setBackgroundResource(R.drawable.badge_view);
			badgeVoice.setBadgeMargin(0, 0);
			badgeVoice.toggle();
			badgeVoice.show();
			badgeVoice.setOnClickListener(new OnClickListener() {
				@SuppressLint("NewApi")
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub

					badgeVoice.hide();
					voicePath = "";
					voiceTimeTv.setVisibility(View.INVISIBLE);
					voiceIv.setBackground(getResources().getDrawable(
							R.drawable.btn_voice_taken));
				}
			});

			voiceTimeTv.setVisibility(View.VISIBLE);
			voiceTimeTv.setText(voiceTime + "'");
		}
	}

	Runnable getDataRun = new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			getRelationHouses();
		}
	};

	// 定义发送请求的方法
	private void getRelationHouses() {

		// 定义发送请求的URL
		String url = Config.SERVER_URL
				+ user.getFunctionlistFromUser(
						Config.FUNCTION_REAL_GETREPAIRAPPLYHOUSELIST).get(0)
						.getFunctionUrl();
		// 发送请求
		String response = "";
		if (Tool.isNetworkAvailable(WritePaperActivity.this)) {
			try {
				RepairApply repairapply = null;
				Map<String, String> map = new HashMap<String, String>();
				map.put("functionCode",
						Config.FUNCTION_REAL_GETREPAIRAPPLYHOUSELIST);
				map.put("relateType", "house");
				List<RelationHouse> relationhouses = new ArrayList<RelationHouse>();
				
				String setsessionid = "";
				user = SingleSample.getInstance(WritePaperActivity.this).getUser();
				if(null != user){
					if(null != user.getSessionId() && !user.getSessionId().equals("")){
						setsessionid = user.getSessionId();
					}
				}
				response = HttpUtil.postRequestSe(url, map,setsessionid);
				response = response.replace("rows", "relationhouses");
				Log.d("XX", response);
				JSONObject jsonobj = new JSONObject(response);
				String rows = jsonobj.getString("relationhouses");
				String message = new JSONObject(response).getString("message");
				String flag = new JSONObject(response).getString("flag");
				// TODO XX
				java.lang.reflect.Type type = new TypeToken<RepairApply>() {
				}.getType();
				java.lang.reflect.Type type1 = new TypeToken<List<RelationHouse>>() {
				}.getType();
				Gson gson = new Gson();
				if (flag.equals("success")) {
					if (null != user.getRepairapply()) {
						repairapply = DataSupport.find(RepairApply.class, user
								.getRepairapply().getId());
						repairapply.setUser(user);
						repairapply.update(user.getRepairapply().getId());
						user.setRepairapply(repairapply);
						user.update(user.getId());
					} else {
						if (flag.equals("success")) {
							repairapply = gson.fromJson(response, type);
							repairapply.setUser(user);
							repairapply.save();
							user.setRepairapply(repairapply);
							user.update(user.getId());
						}
					}
				} else {
					user.setRepairapply(null);
					user.update(user.getId());
					mHandler.obtainMessage(Config.HANDLER_MSG_GETDATA_SUCCESS,
							message).sendToTarget();
				}
				relationhouses = gson.fromJson(rows, type1);
				List<RelationHouse> houses = new ArrayList<RelationHouse>();
				for (RelationHouse house : relationhouses) {
					house.setRepairapply(repairapply);
					house.save();
					houses.add(house);
				}

				repairapply.setRelationhouses(houses);
				repairapply.update(repairapply.getId());
				if (repairapply.isSaved()) {
					user.setRepairapply(repairapply);
					user.update(user.getId());
					Log.d("XX", "Relationhouse save>>>" + repairapply.getId());

				}
				mHandler.obtainMessage(Config.HANDLER_MSG_GETDATA_SUCCESS,
						message).sendToTarget();
			} catch (JsonSyntaxException e) {
				mHandler.sendEmptyMessage(Config.HANDLER_MSG_FAIL_2);
				e.printStackTrace();
			} catch (Exception e) {
				mHandler.sendEmptyMessage(Config.HANDLER_MSG_FAIL_1);
				e.printStackTrace();
			}
		} else {
			mHandler.sendEmptyMessage(Config.HANDLER_MSG_FAIL);
		}
	}

	// 上传文件
	// From: CheckTaskDetailActivity
	private Runnable uploadfile = new Runnable() {

		@Override
		public void run() {
			saveData();
			String url = Config.SERVER_URL
					+ user.getFunctionlistFromUser(
							Config.FUNCTION_REAL_REPAIRAPPLYUPLOADFILE).get(0)
							.getFunctionUrl();
			String result = "";
			String flagstr = "";
			String fileInfo = "";
			int count = 0;
			RepairApply repair1 = new RepairApply();
			Map<String, String> params = new HashMap<String, String>();
			ArrayList<File> files = new ArrayList<File>();
			String imagepath1 = Config.IMAGE_PATH + repair.getProblemImage1();
			String imagepath2 = Config.IMAGE_PATH + repair.getProblemImage2();
			String voicepath1 = Config.VOICE_PATH + repair.getProblemVoice();
			File file1, file2, file3;
			if (!repair.getProblemImage1().equals("")) {
				file1 = new File(imagepath1);
				if (file1.exists()) {
					files.add(file1);
				}
			}
			if (!repair.getProblemImage2().equals("")) {
				file2 = new File(imagepath2);
				if (file2.exists()) {
					files.add(file2);
				}
			}
			if (!repair.getProblemVoice().equals("")) {
				file3 = new File(voicepath1);
				if (file3.exists()) {
					files.add(file3);
				}
			}
			System.out.println(files.size());

			if (files.size() > 0 && !files.isEmpty()) {
				count = files.size();
				params.put("functionCode",
						Config.FUNCTION_REAL_REPAIRAPPLYUPLOADFILE);
				params.put("fileNums", count + "");
				params.put("houseId", repair.getHouseId());
				params.put("areaType_typecode", areaType);
				params.put("sessionId", user.getSessionId());
				UploadService uploadService = new UploadService();

				try {
					System.out.println("result:" + result);
					result = uploadService.uploadFiles(url, params, files);
					System.out.println("result:" + result);
					JSONObject jsonObject = new JSONObject(result);
					flagstr = jsonObject.getString("flag");
					fileInfo = jsonObject.getString("fileInfo");
					message = jsonObject.getString("message");
					java.lang.reflect.Type type = new TypeToken<RepairApply>() {
					}.getType();
					Gson gson = new Gson();
					repair1 = gson.fromJson(fileInfo, type);
					repair.setImage1(repair1.getImage1());
					repair.setImage2(repair1.getImage2());
					repair.setVoice(repair1.getVoice());
					repair.update(repair.getId());
					user.setRepairapply(repair);
					user.update(user.getId());
				} catch (JSONException e) {
					e.printStackTrace();
					mHandler.sendEmptyMessage(Config.HANDLER_MSG_FAIL);
					Log.e("c超时", "c超时");

				} catch (Exception e) {
					e.printStackTrace();
					mHandler.sendEmptyMessage(Config.HANDLER_MSG_FAIL);
					Log.e("s超时", "s超时");
				}

				if (flagstr.equals("success")) {
					// 使用Map封装请求参数
					Map<String, String> map = new HashMap<String, String>();
					map.put("functionCode",
							Config.FUNCTION_REAL_REPAIRAPPLYREPORT);
					map.put("houseId", repair.getHouseId());
					Log.e("房屋id", repair.getHouseId());
					System.out.println("repair.getAreaTypeCode()---11"+repair.getAreaTypeCode());
					map.put("areaType_typecode", repair.getAreaTypeCode());
					map.put("repairObject", repair.getRepairObject());
					/*Log.e("期望时间",
							repair.getExpectTime().substring(0,
									repair.getExpectTime().length() - 6)
									+ ":00");*/
					Log.e("期望时间",ser_start_time_str);
					map.put("expectTime",
							repair.getExpectTime().substring(0,
									repair.getExpectTime().length() - 6)
									+ ":00");
					map.put("problemDescript", repair.getProblemDescript());
					map.put("problemImage1", repair.getImage1());
					map.put("problemImage2", repair.getImage2());
					map.put("problemVoice", repair.getVoice());
					// 定义发送请求的URL
					// 发送请求

					String response = "";
					try {
						String urlstr = Config.SERVER_URL
								+ user.getFunctionlistFromUser(
										Config.FUNCTION_REAL_REPAIRAPPLYREPORT)
										.get(0).getFunctionUrl();
						String setsessionid = "";
						user = SingleSample.getInstance(WritePaperActivity.this).getUser();
						if(null != user){
							if(null != user.getSessionId() && !user.getSessionId().equals("")){
								setsessionid = user.getSessionId();
							}
						}
						response = HttpUtil.postRequestSe(urlstr, map,setsessionid);
						Log.e("post", response);
						String message = new JSONObject(response)
								.getString("message");
						String jsonflag = new JSONObject(response)
								.getString("flag");
						if (jsonflag.equals(Config.CONNECT_SUCCESS2)) {
							mHandler.obtainMessage(Config.HANDLER_MSG_SUCCESS,
									message).sendToTarget();
						} else {

							mHandler.obtainMessage(Config.HANDLER_MSG_FAIL_3,
									message).sendToTarget();

						}
					} catch (JsonSyntaxException e) {
						mHandler.sendEmptyMessage(Config.HANDLER_MSG_JSON_LOGIN_FAIL);
						e.printStackTrace();
					} catch (Exception e) {
						e.printStackTrace();
						mHandler.obtainMessage(Config.HANDLER_MSG_FAIL,
								"联网失败").sendToTarget();
					}
				} else {
					mHandler.obtainMessage(Config.HANDLER_MSG_FAIL_2, "json连接失败")
							.sendToTarget();
				}
			} else {
				Map<String, String> map = new HashMap<String, String>();
				map.put("functionCode", Config.FUNCTION_REAL_REPAIRAPPLYREPORT);
				map.put("houseId", repair.getHouseId());
				System.out.println("repair.getAreaTypeCode()---22"+repair.getAreaTypeCode());
				map.put("areaType_typecode", repair.getAreaTypeCode());
				map.put("repairObject", repair.getRepairObject());
				Log.e("期望时间",
						repair.getExpectTime().substring(0,
								repair.getExpectTime().length() - 6)
								+ ":00");
				map.put("expectTime",
						repair.getExpectTime().substring(0,
								repair.getExpectTime().length() - 6)
								+ ":00");
				map.put("problemDescript", repair.getProblemDescript());
				map.put("problemImage1", "");
				map.put("problemImage2", "");
				map.put("problemVoice", "");
				// 定义发送请求的URL
				// 发送请求

				String response = "";
				try {
					String urlstr = Config.SERVER_URL
							+ user.getFunctionlistFromUser(
									Config.FUNCTION_REAL_REPAIRAPPLYREPORT)
									.get(0).getFunctionUrl();
					String setsessionid = "";
					user = SingleSample.getInstance(WritePaperActivity.this).getUser();
					if(null != user){
						if(null != user.getSessionId() && !user.getSessionId().equals("")){
							setsessionid = user.getSessionId();
						}
					}
					response = HttpUtil.postRequestSe(urlstr, map,setsessionid);
					Log.d("post", response);
					String message = new JSONObject(response)
							.getString("message");
					String jsonflag = new JSONObject(response)
							.getString("flag");
					if (jsonflag.equals(Config.CONNECT_SUCCESS2)) {
						mHandler.obtainMessage(Config.HANDLER_MSG_SUCCESS,
								message).sendToTarget();

					} else {
						mHandler.obtainMessage(Config.HANDLER_MSG_FAIL_1,
								message).sendToTarget();
					}
				} catch (JsonSyntaxException e) {
					mHandler.sendEmptyMessage(Config.HANDLER_MSG_JSON_LOGIN_FAIL);
					e.printStackTrace();
				} catch (Exception e) {
					mHandler.sendEmptyMessage(Config.HANDLER_MSG_FAIL);
					e.printStackTrace();
				}
			}

		}

	};

	Runnable saveDataRun = new Runnable() {
		@Override
		public void run() {
			// TODO Auto-generated method stub
			saveData();
			mHandler.obtainMessage(Config.HANDLER_MSG_LOACALSAVE_SUCCESS)
					.sendToTarget();
		}
	};
	// 获取个人信息
	Runnable getEditPersonRun = new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			Tool.getEditPerson(WritePaperActivity.this);
		}
	};
	
	private void saveData() {

		/* RelationHouse house; */
		if (repair != null) {
			repair.setHouseId(houseid);
			repair.setHouseName(ser_select_house.getText().toString());
			repair.setProblemImage1(imagePath1);
			repair.setProblemImage2(imagePath2);
			repair.setProblemVoice(voicePath);
			repair.setVoicetime(voiceTime + "");
			repair.setProblemDescript(descriptEdit.getText().toString());
			repair.setRepairObject(repairObjectEdit.getText().toString());
			repair.setExpectTime(ser_start_time_str);
			repair.setAreaTypeCode(areaType);
			repair.setRepairPhone(phoneNumber.getText().toString());
			repair.setUser(user);
			repair.update(repair.getId());
			user.setRepairapply(repair);
			user.update(user.getId());
		}
	}

	private void deleteData() {
		repair.setHouseId(houseid);
		repair.setHouseName("");
		repair.setProblemImage1("");

		repair.setProblemImage2("");

		repair.setProblemVoice("");
		repair.setVoicetime("");
		repair.setProblemDescript("");
		repair.setRepairObject("");
		repair.setExpectTime("");
		repair.setAreaTypeCode(areaType);
		repair.setRepairPhone("");
		repair.setUser(user);

		repair.setUser(user);
		repair.update(repair.getId());
		user.setRepairapply(repair);
		user.update(user.getId());
	}

	
	
}
